package com.jxf.demo.parse;

import cn.hutool.json.JSONUtil;
import com.jxf.demo.dto.*;
//import com.jxf.demo.service.impl.DXFCircleParseService;
import com.jxf.demo.service.AbstractDXFParseService;
import com.jxf.demo.service.impl.DXFLineParseService;
import com.jxf.demo.service.impl.DXFPolyLineParseService;
import org.kabeja.dxf.DXFDocument;
import org.kabeja.dxf.DXFLayer;
import org.kabeja.parser.Parser;
import org.kabeja.parser.ParserBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.io.FileInputStream;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class DXFDataParseService {

    /**
     * 注入AbstractDXFParseService抽象类的所有子类方法
     */
    @Autowired
    private Map<String, AbstractDXFParseService> parseServiceMap;

    public void parse(String file) {
//        String file = "D:/application/cad/project/16-1.dxf";
        Parser parser = ParserBuilder.createDefaultParser();
        try (FileInputStream inputStream = new FileInputStream(file)) {
            parser.parse(inputStream, "UTF-8");
            DXFDocument doc = parser.getDocument();
            DXFLayer dxfLayer = doc.getDXFLayer("0");

            List<DXFPointInfo> allPointList = new ArrayList<>();
            // 循环所有图形解析实现类并调用对应的解析方法
            parseServiceMap.forEach((name, service) -> {
                List<DXFPointInfo> pointInfoList = service.parse(dxfLayer);
                allPointList.addAll(pointInfoList);
            });
            for (DXFPointInfo pointInfo : allPointList) {
                List<StraightLine> points = pointInfo.getPoints();
                for (StraightLine line : points){
                    StraightLine.Coordinate start = line.getStart();
                    start.setX(start.getX().setScale(1, RoundingMode.HALF_UP));
                    start.setY(start.getY().setScale(1,RoundingMode.HALF_UP));

                    StraightLine.Coordinate end = line.getEnd();
                    end.setX(end.getX().setScale(1,RoundingMode.HALF_UP));
                    end.setY(end.getY().setScale(1,RoundingMode.HALF_UP));
                }
            }
            System.out.println("result:" + JSONUtil.toJsonPrettyStr(allPointList));
            if (CollectionUtils.isEmpty(allPointList)) {
                throw new RuntimeException("解析结果为空");
            }
            if (allPointList.size() > 1) {
                throw new RuntimeException("包含多个图形");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
